package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.domain.Goods;
import com.qf.util.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/19
 */
public class GoodsDaoImpl implements GoodsDao {
    QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDatasource());
    @Override
    public Long findTotalCount(int typeId) {
        String sql = "select count(0) from tb_goods where typeid = ?";
        try {
            return (long)queryRunner.query(sql, new ScalarHandler(),typeId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Goods> findData(int typeId, int startIndex, int pageSize) {
        String sql = "select id,name,pubdate,picture,price,star,intro,typeid from tb_goods where typeid = ? limit ?, ?";
        try {
            List<Goods> goodsList = queryRunner.query(sql , new BeanListHandler<>(Goods.class), typeId, startIndex, pageSize);
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Goods findById(int id) {
        String sql = "select id,name,pubdate,picture,price,star,intro,typeid from tb_goods where id = ?";
        try {
            Goods goods  = queryRunner.query(sql , new BeanHandler<>(Goods.class), id);
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }
}
